package cn.quevo.client.jssc;

import cn.quevo.common.lang.NumberUtils;
import cn.quevo.common.lang.StringUtils;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

public class Test {
    SerialPort serialPortLed;
    boolean isFirst = true;

    private void checkLed() throws SerialPortException {
        if (serialPortLed == null) {
            serialPortLed = new SerialPort("COM5"); //输入你的串口号
        }
        if (!serialPortLed.isOpened()) {
            serialPortLed.openPort();
            serialPortLed.addEventListener(listenr);
        }
        serialPortLed.setParams(SerialPort.BAUDRATE_19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    }

    private void openLed() {
        try {
            checkLed();
            sendPortData(serialPortLed, "@0008010000DE", false);
            /*new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        read();
                        Thread.sleep(125);
                    } catch (SerialPortException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            } ).start();*/
//            read();
//            read2();
        } catch (SerialPortException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送串口命令
     */
    private void sendPortData(SerialPort ComPort, String data, boolean isHex) throws SerialPortException {
        System.out.println(ComPort.isOpened());
        if (ComPort != null && ComPort.isOpened()) {
            //是否16进制的命令，如果是，走上面，如果是字符型的命令，直接走下面
            /*if (isHex) {
                ComPort.writeBytes(MyFunc.HexToByteArr(data));
            } else {
                ComPort.writeString(data);
            }*/
            System.out.println("DFDSDF");

            System.out.println( ComPort.writeString(data));
        }
    }

    private void read() throws SerialPortException, InterruptedException {
       /* byte[] bytes = serialPortLed.readBytes();
        for (byte b : bytes) {
            System.out.print(b);
        }
        System.out.println("===============");*/
       while (true) {
           Thread.sleep(1000);
           System.out.println("======");
           byte[] bs = serialPortLed.readBytes(128);
           if (bs != null && bs.length > 0) {
               for (byte b : bs){
                   System.out.print(b);
               }
           }
//           System.out.println(serialPortLed.readBytes(128));
           System.out.println("------");
           System.out.println();
       }
    }
    private void read2() throws SerialPortException, InterruptedException {
       /* byte[] bytes = serialPortLed.readBytes();
        for (byte b : bytes) {
            System.out.print(b);
        }

        System.out.println("===============");*/
       Thread.sleep(1000);
        System.out.println("======");
        byte[] bs = serialPortLed.readBytes(32);
        if (bs != null && bs.length > 0) {
            for (byte b : bs){
                System.out.print(b);
            }
        }
//           System.out.println(serialPortLed.readBytes(128));
        System.out.println("------");
        System.out.println();
    }
    private String LastCardUID = "";
    private StringBuilder DataBuf = new StringBuilder();

    SerialPortEventListener listenr = new SerialPortEventListener() {
        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            if (serialPortEvent.isRXCHAR()) {
                try {
                    String data = serialPortLed.readString(serialPortEvent.getEventValue());
//                    data = StringUtils.isBlank(data)?"":data.replaceAll("0*$","");
                    System.out.println("data："+data);
//                    data = data.replace("0","");
                    boolean boolStartTag = data.contains("@");
                    System.out.println("BOOLSTART: "+boolStartTag );
                    if (boolStartTag) {
                        DataBuf.setLength(0);
                    }
                    String RecvData = boolStartTag ? data.substring(data.indexOf("@")) : data;
                    DataBuf.append(RecvData);
                    System.out.println("RecvData: "+RecvData.toString());
                    System.out.println("DataBuf: "+DataBuf.toString());
                    if (DataBuf.length() > 4) {
                        int CmdLength = NumberUtils.toInt(DataBuf.toString().substring(1,5));
                        System.out.println("CmdLength: "+CmdLength);
                        if (CmdLength + 5 == DataBuf.length()) {
                            System.out.println("RECV: "+DataBuf.toString());
                            if (DataBuf.toString().substring(5,11).equals("010000")) {
                                LastCardUID = DataBuf.toString().substring(11, 19);
                            }
                        }
                    }
                    System.out.println("LastCardUID："+LastCardUID);

                    if (!StringUtils.isBlank(LastCardUID) && isFirst) {
                        Thread.sleep(1200);
                        writeAmt();
                    }

                   /* if (serialPortEvent.getEventValue() > 0) {
                        System.out.println("come into return");
                        System.out.println("serialPortEvent.getEventType():" + serialPortEvent.getEventType());
                        System.out.println("serialPortEvent.getPortName():" + serialPortEvent.getPortName());
                        System.out.println("serialPortEvent.getEventValue():" + serialPortEvent.getEventValue());
                        //以16进制的方式读取串口返回数据
                        System.out.println("read form serial:" + serialPortEvent.getPortName() + "   " + serialPortLed.readHexString(serialPortEvent.getEventValue()));
                        System.out.println(serialPortEvent.getEventValue());
                        System.out.println("SSS  "+serialPortLed.readString(serialPortEvent.getEventValue()));
                    }

                    //我的机器比较烂，如果不停读取串口会导致GCLOG不停打印，所以每次休眠个250ms
                    Thread.sleep(250);*/
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    };

    private void writeAmt() throws SerialPortException {
       if (StringUtils.isBlank(LastCardUID))  {
            System.out.println("请先寻卡!!");
            return;
        }
        String CmdString = String.format("@0034010100%s%018d", LastCardUID, 100);
        int cSum = 0;
        for (byte v : CmdString.substring(5).getBytes()) {
            cSum += v;
        }
        CmdString += String.format("%2X",0xff- (cSum & 0xff));

        serialPortLed.writeString(CmdString);
        System.out.println("SENDER: "+CmdString);
        isFirst = false;
    }
    public static void main(String[] args) throws InterruptedException {
        Test t = new Test();
        t.openLed();
//        String test = "@00340100001D97A07800000000009999850088";
//        System.out.println(test.replaceAll("0*$",""));
//        System.out.println(test.substring(5,11));
//        System.out.println(test.substring(11,19));
//        System.out.println(test.length());
       /* System.out.println(String.format("@0034010100%s%018d", "1D97A078", 10000));
        String CmdString = "@00340101001D97A078000000000000010000";
        int cSum = 0;
        for (byte v : CmdString.substring(5).getBytes()) {
            cSum += v;
        }
        CmdString += String.format("%2x",0xff- (cSum & 0xff)).toUpperCase();
        System.out.println(CmdString);*/
    }
}
